package com.codebuffer.nowcoder;

public class ReverseSentence {
    public String ReverseSentence(String str) {
        StringBuilder sb = new StringBuilder();
        String[] s = str.split(" ");
        for (int i = s.length - 1; i >= 0; i--) {
            if(i==0){
                sb.append(s[i]);
            }else {
                sb.append(s[i]);
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    public static String ReverseSentence2(String str) {
        StringBuilder sb = new StringBuilder();
        StringBuilder s = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            if(str.charAt(i)==' '){
                sb.append(s.reverse()).append(str.charAt(i));
                s = new StringBuilder();
                continue;
            }
            s.append(str.charAt(i));
        }
        sb.append(s.reverse());
        return sb.toString();
    }

    public static String ReverseSentence3(String str) {
        StringBuilder sb = new StringBuilder();
        int end = str.length();
        int start = str.lastIndexOf(" ");
        while(start>=0){
            sb.append(str.substring(start+1,end)).append(" ");
            end = start;
            str = str.substring(0,end);
            start = str.lastIndexOf(" ");
        }
        sb.append(str);
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(ReverseSentence3("I am a student."));
    }
}
